package com.example.controller;

        import com.example.bean.ApiResult;
        import com.example.bean.Book;
        import com.example.bean.Collect;
        import com.example.service.CollectService;
        import com.example.utils.ApiResultHandler;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.*;

        import java.util.List;

@RestController
@RequestMapping("/collect")
@CrossOrigin
public class CollectController {

    @Autowired
    private CollectService collectService;

    /**
     * 添加收藏
     * 将收藏状态置为1
     * @param collect 收藏实体类
     * @return ApiResult
     */
    @PostMapping("/{userId}/{bookId}")
    public ApiResult addCollect(@PathVariable int userId, @PathVariable String bookId){
        int res = collectService.insertCollect(userId,bookId);
        if(res!=0){
            return ApiResultHandler.buildApiResult(200, "添加收藏成功",res);
        }
        return ApiResultHandler.buildApiResult(400, "添加收藏失败",res);
    }

    /**
     * 删除收藏
     * 完成删除后将收藏状态置为0
     * @param userId 用户ID
     * @param bookId 书籍ID
     * @return ApiResult
     */
    @DeleteMapping("/{userId}/{bookId}")
    public ApiResult deleteCollect(@PathVariable int userId, @PathVariable String bookId){
        int result = collectService.deleteCollect(userId, bookId);
        if(result != 0){
            return ApiResultHandler.buildApiResult(200, "删除收藏成功",result);
        }
        return ApiResultHandler.buildApiResult(400, "删除收藏失败",result);
    }

    /**
     * 查询某个用户收藏的所有书籍
     * @param userId 用户ID
     * @return ApiResult
     */
    @GetMapping("/user/{userId}")
    public ApiResult getUserCollect(@PathVariable int userId){
        List<Book> books = collectService.selectBookByUserId(userId);
        if( books!=null && books.isEmpty()){
            return ApiResultHandler.buildApiResult(400, "暂无数据",books);
        }
        return ApiResultHandler.buildApiResult(200, "查询用户收藏成功", books);
    }

    /**
     * 查询某个用户是否收藏某本书
     * @param userId 用户ID
     * @return ApiResult
     */
    @GetMapping("/select/{userId}/{bookId}")
    public ApiResult judgeUserCollect(@PathVariable int userId, @PathVariable String bookId){
        Collect collect = collectService.judgeUserCollect(userId, bookId);
        if( collect!=null){
            return ApiResultHandler.buildApiResult(200, "已收藏",collect);
        }
        return ApiResultHandler.buildApiResult(400, "未收藏", collect);
    }

    /**
     * 查询某本书被收藏的数量
     * @param bookId 书籍ID
     * @return ApiResult
     */
    @GetMapping("/count/{bookId}")
    public ApiResult getBookCollectCount(@PathVariable String bookId){
        int count = collectService.selectBookCollected(bookId);
        return ApiResultHandler.buildApiResult(200, "查询书籍被收藏数量成功", count);
    }
}
